﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Management;  
using System.Management.Automation;
using System.Management.Automation.Runspaces;

using System.ServiceProcess;
using System.Configuration.Install;
using Microsoft.Win32;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void Form1_Activated(object sender, EventArgs e)
        {
            this.textBox_service1.Focus();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = @"可执行文件|*.exe";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //将文件夹路径显示
                //MessageBox.Show(P_File_Folder.SelectedPath);//选定目录后打印路径信息
                this.textBox_service1.Text = openFileDialog.FileName;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(openFileDialog.FileName);
                Image image = icon.ToBitmap();
                this.pictureBox1.BackgroundImage = image;
            }
        }
        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = @"可执行文件|*.exe";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //将文件夹路径显示
                //MessageBox.Show(P_File_Folder.SelectedPath);//选定目录后打印路径信息
                this.textBox_service2.Text = openFileDialog.FileName;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(openFileDialog.FileName);
                Image image = icon.ToBitmap();
                this.pictureBox2.BackgroundImage = image;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }



        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = @"可执行文件|*.exe";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //将文件夹路径显示
                //MessageBox.Show(P_File_Folder.SelectedPath);//选定目录后打印路径信息
                this.textBox_service3.Text = openFileDialog.FileName;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(openFileDialog.FileName);
                Image image = icon.ToBitmap();
                this.pictureBox3.BackgroundImage = image;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = @"可执行文件|*.exe";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //将文件夹路径显示
                //MessageBox.Show(P_File_Folder.SelectedPath);//选定目录后打印路径信息
                this.textBox_service4.Text = openFileDialog.FileName;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(openFileDialog.FileName);
                Image image = icon.ToBitmap();
                this.pictureBox4.BackgroundImage = image;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = @"可执行文件|*.exe";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //将文件夹路径显示
                //MessageBox.Show(P_File_Folder.SelectedPath);//选定目录后打印路径信息
                this.textBox_service5.Text = openFileDialog.FileName;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(openFileDialog.FileName);
                Image image = icon.ToBitmap();
                this.pictureBox5.BackgroundImage = image;
            }
        }
        //操作，包含创建JAVA_HOME环境，添加java的path，mysql数据库的安装，及各exe程序注册为windows服务
        private void button_post_Click(object sender, EventArgs e)
        {
            //Console.WriteLine("你好啊美女！");
            //对powershell脚本进行修改
            CallPowershell();
        }
        //脚本执行程序
        private bool CallPowershell()
        {


            //读取路径然后依据路径进行开启服务
            string[] paths = new string[5];
            paths[0] = this.textBox_service1.Text;
            paths[1] = this.textBox_service2.Text;
            paths[2] = this.textBox_service3.Text;
            paths[3] = this.textBox_service4.Text;
            paths[4] = this.textBox_service5.Text;
            int j = 0;//安装服务序号
            for (int i = 0; i < 5; i++)
            {   
                if (!string.IsNullOrEmpty(paths[i]))
                {
                    j++;
                    string[] sArray = paths[i].Split('\\');// 一定是单引 
                    string temp = sArray[sArray.Length - 1];
                    //去掉.exe
                    string serviceName = temp.Replace(".exe", string.Empty);
                    serviceName = serviceName.Trim();
                    Console.WriteLine(j+".准备安装:" + serviceName+"\n");
                    //判断服务是否存在

                    if (this.IsServiceExisted(serviceName))
                    {
                        //this.UninstallService(serviceName);
                        //在命令行上提醒服务已存在
                        Console.WriteLine("服务<<" + serviceName + ">>已存在，跳过安装此服务！\n");
                    }
                    else
                    {
                        //安装服务
                        var result = this.InstallService(paths[i], serviceName);
                        if (result)
                        {
                            Console.WriteLine("安装成功！\n\n准备启动服务"+serviceName+"\n");
                            //等待服务可以被启动
                            while (!IsServiceExisted(serviceName)) ;
                            Thread.Sleep(5 * 1000);
                            //打开服务
                            if (checkBox1.CheckState == CheckState.Checked)
                            {
                                ServiceStart(serviceName);
                                Console.WriteLine(serviceName + "启动成功！\n");
                            }
                        }
                        else
                        {
                            Console.WriteLine("安装失败！\n");
                        }
                    }

                  
                }
            }

            return true;
        }


        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //安装服务，通过注册表实现
        private Boolean InstallService(string path,string serviceName)
        {
            try
            {
                //获取当前位置
                string currentPath = Environment.CurrentDirectory;
                //Console.WriteLine("当前路径{0}", currentPath);
                RegistryKey key = Registry.LocalMachine;
                ////添加必要的键值
                //service.SetValue("DisplayName", serviceName);
                //service.SetValue("ErrorControl", 0x01);
                //service.SetValue("ImagePath", currentPath+"\\srvany.exe");
                //service.SetValue("ObjectName", "LocalSystem");
                //service.SetValue("Start", 0x02);
                //service.SetValue("Type", 0x10);

                Process.Start("sc", "create " + serviceName + " binPath= \"" + currentPath + "\\srvany.exe\"  displayname= \"" + serviceName + "\" start= auto");
                //Console.WriteLine("sc create " + serviceName + " binPath= \"" + currentPath + "\\srvany.exe\"  displayname= \"" + serviceName + "\" start= auto");
                //添加子项parameters
                RegistryKey service2 = key.CreateSubKey(@"system\currentcontrolset\services\" + serviceName + @"\parameters");
                service2.SetValue("application", path.Replace("\\", "\\\\"));
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:{0}",ex.Message);
                return false;
            }

        }

        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        //启动服务
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                //if (control.Status == ServiceControllerStatus.Stopped)
                //{
                    try
                    {
                        control.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception:{0}", ex);
                    }
                //}
            }
        }

        //停止服务
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }

    }
}
